import { defineComponent, ref, shallowRef, onMounted, onBeforeUnmount, reactive } from 'vue'
import type { RunMapType } from './typings'
import useAMap from '~/hooks/useAMap'
import lamppostOne from '~/assets/singleLamp/ic_lamp_1.png'
import lamppostTwo from '~/assets/singleLamp/ic_lamp_2.png'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'RunMap',
  props: ['id', 'initCallback', 'getMapZoom'],
  emits: ['handleLamppostInfo'],
  setup(props: RunMapType, { emit, expose }) {
    const mapDomRef = ref()
    const state = reactive<any>({
      loca: null,
      lamppost: null,
      detail: null
    })
    const [mapRef, aMapRef] = useAMap(
      props.id,
      {
        zoom: 12,
        mapStyle: 'amap://styles/whitesmoke'
      },
      initAMap
    )
    // 获取租户设置的坐标

    const getCurrentTenant = useVuexGetters('user', ['userAddressInfo'])
    // 设置地图中心点和地图层级
    const handleSetMapInfo = () => {
      mapRef.value.setCenter([
        getCurrentTenant.userAddressInfo.value.lon,
        getCurrentTenant.userAddressInfo.value.lat
      ])
    }

    //  灯杆点
    const markerLabelsLayer = async (list: any) => {
      const arr: any[] = []
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        arr.push({
          type: 'Feature',
          properties: {
            name: item.name,
            detail: item,
            icon: item.num === 1 ? lamppostOne : lamppostTwo
          },
          geometry: {
            type: 'Point',
            coordinates: [Number(item.lon), Number(item.lat)]
          }
        })
      }
      const geo = new window.Loca.GeoJSONSource({
        data: {
          type: 'FeatureCollection',
          features: arr
        }
      })
      state.lamppost.setSource(geo)
      state.lamppost.setStyle({
        text: {
          content: (feat: any) => feat.properties.name
        },
        icon: (index: any, feat: any) => feat.properties.icon,
        iconSize: [20, 20]
      })

      state.loca.add(state.lamppost)
    }
    //  标点
    const marker = shallowRef()
    const markerLayer = (row: any) => {
      if (marker.value) {
        mapRef.value.remove(marker.value)
      }
      const icon = row.num === 1 ? lamppostOne : lamppostTwo
      const content = `<div style='position: relative;transform: translate(-50%, -170%);'>
       <div style='white-space: nowrap;color: red;font-size: 14px;'>${row.content}</div>
       <div style='position: absolute;left: 50%;transform: translate(-50%, 0);'>
         <img src='${icon}' width='34px' height='38px' />
       </div>
     </div>`
      marker.value = new aMapRef.value.Marker({
        position: row.markers,
        content,
        offset: [0, 0]
      })
      mapRef.value.add(marker.value)
      mapRef.value.setFitView()
    }
    //  地图初始化
    async function initAMap() {
      await props.initCallback()

      //  地图缩放
      mapRef.value.on('zoomend', () => {
        props.getMapZoom?.()
      })
      state.loca = new window.Loca.Container({
        map: mapRef.value
      })
      //  灯杆图层
      state.lamppost = new window.Loca.IconLayer({
        zIndex: 300,
        opacity: 1,
        visible: true
      })

      //  地图点击
      mapRef.value.on('click', (e: any) => {
        const feat = state.lamppost.queryFeature(e.pixel.toArray())
        if (feat) {
          state.detail = feat.properties.detail
          emit('handleLamppostInfo', state.detail)

          const markers = [state.detail.lon, state.detail.lat]
          const content = state.detail.name
          const num = state.detail.num
          markerLayer({ markers, content, num })
        }
      })
    }

    onMounted(() => {})
    onBeforeUnmount(() => {
      mapRef.value.clearMap()
      mapRef.value.destroy()
    })

    expose({
      map: mapRef,
      aMap: aMapRef,
      handleSetMapInfo,
      markerLabelsLayer,
      markerLayer
    })
    return () => (
      <>
        <section id={props.id} ref={mapDomRef}></section>
      </>
    )
  }
})
